package org.qiuer.compile;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.qiuer.exception.Const;
import org.qiuer.exception.ERuntime;
import org.qiuer.exception.IException;

import java.io.File;
import java.nio.charset.StandardCharsets;

public class ASTCompiler {
  public final static String ES_SRC_PATH = "es/src";
  public final static String ES_OUTPUT_PATH = "es/out";

  /**
   * 将es6的代码编译为json。
   *
   * @return
   * @throws IException
   */
  public static void compile() throws IException {
    try {
      Process process = Runtime.getRuntime().exec("node ./fe/parse.js " +  ES_SRC_PATH + " " + ES_OUTPUT_PATH);
      int code = process.waitFor();
      if (code != 0)
        throw new ERuntime(Const.EXCEPTION.COMPILE_FAILURE, IOUtils.toString(process.getErrorStream(), StandardCharsets.UTF_8));
    } catch (Exception e) {
      e.printStackTrace();
      throw new ERuntime(Const.EXCEPTION.COMPILE_FAILURE, "编译失败:" + e.getMessage());
    }
  }
}
